package com.market.config;

import com.market.interceptor.CrossOriginInterceptor;
import com.market.interceptor.LoginInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(WebConfig.class);
    
    // 不需要权限验证的路径
    private static final List<String> PUBLIC_PATHS = Arrays.asList(
        "/user/login", 
        "/error"
    );

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        logger.info("配置拦截器...");
        
        // 登录拦截器，排除公开接口
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**") // 拦截所有请求
                .excludePathPatterns(PUBLIC_PATHS) // 排除公开路径
                .order(1);
        logger.info("已配置登录拦截器，排除路径: {}", PUBLIC_PATHS);
                
        logger.info("拦截器配置完成");
    }

    /**
     * 允许跨域的全局配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        logger.info("配置全局CORS...");
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000", "http://127.0.0.1:5500")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .exposedHeaders("Access-Control-Allow-Headers", "Access-Control-Allow-Methods", 
                               "Access-Control-Allow-Origin", "Access-Control-Max-Age", "X-Frame-Options")
                .allowCredentials(true)
                .maxAge(3600);
        logger.info("全局CORS配置完成");
    }
}
